package com.joysuch.wwyt.risk.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.common.base.Splitter;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpJob;
import com.joysuch.wwyt.bp.entity.investigate.BpInvestigatePlan;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpInvestigatePlanRepository;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.entity.BaseTypeGroup;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.repository.BaseTypeGroupDao;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.DateUtils;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.entity.*;
import com.joysuch.wwyt.risk.entity.dto.RiskEvaluationPlanDetailDto;
import com.joysuch.wwyt.risk.entity.vo.RiskMeasureTypeNode;
import com.joysuch.wwyt.risk.enums.ControlLevels;
import com.joysuch.wwyt.risk.mapper.RiskPointMapper;
import com.joysuch.wwyt.risk.repository.*;
import com.joysuch.wwyt.risk.service.*;
import com.joysuch.wwyt.risk.util.RiskEvalExcelUtil;
import com.joysuch.wwyt.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author ZhaoQiuWei
 * @Date 2022/1/6 15:36
 */
@Service
@Slf4j
public class RiskStorePointEvalExcelExportServiceImpl implements RiskStorePointEvalExcelExportService {


    @Autowired
    private RiskEvaluationAnalyzeWayDao analyzeWayDao;
    @Autowired
    private RiskEvaluationAnalyzeMethodDao analyzeMethodDao;
    @Autowired
    private RiskEvaluationTargetTypeDao targetTypeDao;
    @Autowired
    private RiskEvaluationTargetItemDao targetItemDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;
    @Autowired
    private BaseTypeGroupDao baseTypeGroupDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private RiskPointTypeDao riskPointTypeDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private RiskEvaluationTempleService evaluationTempleService;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private RiskEvaluationBusinessService riskEvaluationBusinessService;
    @Autowired
    private RiskPointEvaluationBusinessDao pointEvaluationBusinessDao;
    @Autowired
    private RiskPointEvaluationItemDao riskPointEvaluationItemDao;
    @Autowired
    private BaseRoleDataAuthService baseRoleDataAuthService;
    @Autowired
    private RiskPointEvaluationDetailDao riskPointEvaluationDetailDao;
    @Autowired
    private RiskMeasureTypeService riskMeasureTypeService;
    @Autowired
    private RiskPointMapper riskPointMapper;
    @Autowired
    private RiskControlLevelService riskControllevelsService;
    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    private RiskHiddenDangerContentService riskHiddenDangerContentService;
    @Autowired
    private BpInvestigatePlanRepository planRepository;
    @Autowired
    private RiskEvaluationControlDao riskEvaluationControlDao;
    @Autowired
    private RiskPointEvalExcelExportService pointEvalExcelExportService;


    @Override
    public SXSSFWorkbook exportDistrictEvaluationExcel(Integer isTemplate, Integer shared) {
        return exportDistrictEvaluationExcel(isTemplate,shared,null);
    }

    /**
     * 区域风险点/风险点库 模板/数据导出
     *
     * @param isTemplate 0模板导出 1新数据导出 2旧数据按新模板导出
     * @param shared     0/null 区域风险点  1风险点库
     * @return
     */
    @Override
    public SXSSFWorkbook exportDistrictEvaluationExcel(Integer isTemplate, Integer shared,String districtIds) {
        long ey = System.currentTimeMillis();
        RiskExcelModelBean bean = new RiskExcelModelBean();
        SXSSFWorkbook workbook = new SXSSFWorkbook();//一个全新的工作薄
        bean.setWorkbook(workbook);
        List<SimpleSelectListBean> wayList = evaluationTempleService.getAllAnalyzeWay(2);
        int sheetIndex = 1;
        bean.setSheetIndex(sheetIndex);
        ExcelExportToolMapBean toolBean = new ExcelExportToolMapBean();
        if (isTemplate != null && (isTemplate.intValue() == 1 || isTemplate == 0)) {
            toolBean = getExcelExportToolMapBean(shared, isTemplate,districtIds);
        }
        RiskEvaluationControl control = riskEvaluationControlDao.findByName("风险评估导入模板");
        RiskEvaluationControl storePointCtor = riskEvaluationControlDao.findByName("风险点库导入模板");
        //默认全国版
        Integer measureTypeFlag = 1;
        //默认横版
        Integer storePointFlag = 0;
        if (control == null) {
            measureTypeFlag = 1;
        } else {
            measureTypeFlag = control.getSwitchState();
        }
        if (storePointCtor == null) {
            storePointFlag = 0;
        } else {
            storePointFlag = storePointCtor.getSwitchState();
        }
        // 设置管控措施
        Integer maxTypeLevel = (shared == null || shared == 0) ? Integer.valueOf(3) : Integer.valueOf(1);
        // 获取三级管控措施列表
        List<RiskMeasureTypeNode> childrenTypes = riskMeasureTypeService.getAllChilds(null);
        bean.setAllMeasureTypes(childrenTypes);
        bean.setMaxTypeLevel(maxTypeLevel);

        // 生成动态管控措施类型列表
        if (shared == null || shared == 0) {
            for (SimpleSelectListBean selectBean : wayList) {
                bean = pointEvalExcelExportService.createSheetData(bean, selectBean.getValue(), isTemplate, shared, toolBean, measureTypeFlag, storePointFlag);
                sheetIndex = bean.getSheetIndex() + 1;
                bean.setSheetIndex(sheetIndex);
            }
            createRiskMeasureTypeSheet(workbook, bean);
        } else {
            for (SimpleSelectListBean selectBean : wayList) {
                bean = createSheetData(bean, selectBean.getValue(), isTemplate, shared, toolBean, measureTypeFlag, storePointFlag);
                sheetIndex = bean.getSheetIndex() + 1;
                bean.setSheetIndex(sheetIndex);
            }
        }
        log.info("评估导出用时   :::::::::::::" + (System.currentTimeMillis() - ey));
        return bean.getWorkbook();
    }

    private ExcelExportToolMapBean getExcelExportToolMapBean(Integer shared, Integer isTemplate,String districtIds) {
        ExcelExportToolMapBean bean = new ExcelExportToolMapBean();
        Map<Long, BaseUser> userMap = new HashMap();
        List<BaseUser> users = baseUserDao.findAll();
        if (!CollectionUtils.isEmpty(users)) {
            userMap = users.stream().collect(Collectors.toMap(r -> r.getId(), r -> r));
        }
        Map<Long, BpDepart> departMap = new HashMap<>();
        List<BpDepart> departs = bpDepartDao.findAll();
        if (!CollectionUtils.isEmpty(departs)) {
            departMap = departs.stream().collect(Collectors.toMap(r -> r.getId(), r -> r));
        }

        Map<Long, RiskControllevels> controLevelMap = new HashMap<>();
        List<RiskControllevels> controlLevelList = riskControllevelsService.getAllLevels();
        if (!CollectionUtils.isEmpty(controlLevelList)) {
            controLevelMap = controlLevelList.stream().collect(Collectors.toMap(r -> r.getCode(), r -> r));
        }

        Map<Long, RiskEvaluationTargetItem> targetItemMap = new HashMap<>();
        List<RiskEvaluationTargetItem> targetItemList = targetItemDao.findAll();
        if (!CollectionUtils.isEmpty(targetItemList)) {
            targetItemMap = targetItemList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r));
        }


        Map<String, RiskPointType> pointTypeMap = new HashMap<>();
        List<RiskPointType> pointTypeList = riskPointTypeDao.findAll();
        if (!CollectionUtils.isEmpty(pointTypeList)) {
            pointTypeMap = pointTypeList.stream().collect(Collectors.toMap(r -> r.getCode(), r -> r));
        }

        Map<Long, List<RiskPointEvaluationItem>> evaluationItemMap = new HashMap<>();

        List<Long> districtIdsList = new ArrayList<>();
        if (StringUtils.isNotBlank(districtIds)){
            districtIdsList = Splitter.on(Constant.SPLIT_COMMA).trimResults().splitToList(districtIds.trim()).stream().map(Long::new).collect(Collectors.toList());
        }

        List<Long> departIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        List<RiskPoint> points = new ArrayList<>();
        if (shared == null || shared == 0) {
            if (CollectionUtils.isEmpty(districtIdsList)){
                points = riskPointDao.findByDistrictDeptAndTimeIsNotNull(departIds);
                List<RiskPointEvaluationItem> evaluationItemList = riskPointEvaluationItemDao.findAll();
                if (!CollectionUtils.isEmpty(evaluationItemList)) {
                    evaluationItemMap = evaluationItemList.stream().collect(Collectors.groupingBy(RiskPointEvaluationItem::getPointEvaluationId));
                }
            }else {
                points = riskPointDao.findByDistrictAndTimeIsNotNull(departIds,districtIdsList);
                List<Long> pointIds = points.stream().map(RiskPoint::getId).collect(Collectors.toList());
                List<RiskPointEvaluationItem> evaluationItemList = riskPointEvaluationItemDao.findAllByPointId(pointIds);
                if (!CollectionUtils.isEmpty(evaluationItemList)) {
                    evaluationItemMap = evaluationItemList.stream().collect(Collectors.groupingBy(RiskPointEvaluationItem::getPointEvaluationId));
                }
            }
        } else if (shared == 1) {
            points = riskPointDao.findByTimeIsNotNullAndShared();
        }
        Map<Long, RiskMeasureType> measureMap = new HashMap<>();
        Map<Long, List<RiskEvaluationPlanDetailDto>> planDetailMap = new HashMap<>();
        Map<Long, List<RiskHiddenDangerContent>> dangerContentMap = new HashMap<>();
        Map<Long, List<BpInvestigatePlan>> investigatePlanMap = new HashMap<>();
        List<RiskMeasureType> topTypeList = riskMeasureTypeService.getTopTypes();
        List<BaseTypeGroupItem> controlTypeGroupItemList = new ArrayList<>();
        Map<Long, BaseTypeGroupItem> controlTypeGroupItemMap = new HashMap<>();
        if (shared != null && shared == 1) {
            BaseTypeGroup controlType = baseTypeGroupDao.findByName("管控措施");
            if (controlType != null) {
                controlTypeGroupItemList = baseTypeGroupItemDao.findByTypeGroupId(controlType.getId());
                if (!CollectionUtils.isEmpty(controlTypeGroupItemList)) {
                    controlTypeGroupItemMap = controlTypeGroupItemList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r));
                }
            }
        }
        if (isTemplate != null && isTemplate.equals(1)) {
            List<RiskMeasureType> measureList = riskMeasureTypeService.getAll();
            if (!CollectionUtils.isEmpty(measureList)) {
                measureMap = measureList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r));
            }

            List<RiskEvaluationPlanDetailDto> planDetailBeanList = riskPointMapper.getAllPlanDetail(Context.getCurrentTenantId(), Context.getCompanyCode());
            if (!CollectionUtils.isEmpty(planDetailBeanList)) {
                planDetailMap = planDetailBeanList.stream().collect(Collectors.groupingBy(RiskEvaluationPlanDetailDto::getDetailId));
            }
            List<RiskHiddenDangerContent> dangerContentList = riskHiddenDangerContentService.findAll();
            if (!CollectionUtils.isEmpty(dangerContentList)) {
                dangerContentMap = dangerContentList.stream().collect(Collectors.groupingBy(RiskHiddenDangerContent::getDetailId));
            }

            List<BpInvestigatePlan> investigatePlans = planRepository.getEvaluationPlans();
            if (!CollectionUtils.isEmpty(investigatePlans)) {
                investigatePlanMap = investigatePlans.stream().collect(Collectors.groupingBy(BpInvestigatePlan::getHiddenDangerContentId));
            }
        }

        List<BpJob> jobList = bpJobDao.findAll();
        Map<Long, String> jobMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(jobList)) {
            jobMap = jobList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r.getName()));
        }

        boolean stablePointContrFlag = false;
        RiskEvaluationControl stablePointContr = riskEvaluationControlDao.findByName(BaseConfigCodes.WWYT_RISK_NAME);
        if (stablePointContr != null && stablePointContr.getSwitchState().equals(1)) {
            stablePointContrFlag = true;
        }

        List<BaseTypeGroupItem> dataSourceList = new ArrayList<>();
        Map<Long, String> dataSourceMap = new HashMap<>();
        BaseTypeGroup tGroup = baseTypeGroupDao.findByName("取数来源");
        if (tGroup != null) {
            dataSourceList = baseTypeGroupItemDao.findByTypeGroupId(tGroup.getId());
            if (!CollectionUtils.isEmpty(dataSourceList)) {
                dataSourceMap = dataSourceList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r.getName()));
            }
        }

        List<BaseTypeGroupItem> troubleshootingTypeList = new ArrayList<>();
        Map<Long, String> troubleshootingTypeMap = new HashMap<>();
        BaseTypeGroup tsGroup = baseTypeGroupDao.findByName("排查类型");
        if (tsGroup != null) {
            troubleshootingTypeList = baseTypeGroupItemDao.findByTypeGroupId(tsGroup.getId());
            if (!CollectionUtils.isEmpty(troubleshootingTypeList)) {
                troubleshootingTypeMap = troubleshootingTypeList.stream().collect(Collectors.toMap(r -> r.getId(), r -> r.getName()));
            }
        }

        bean.setUserMap(userMap);
        bean.setDepartMap(departMap);
        bean.setControLevelMap(controLevelMap);
        bean.setTargetItemMap(targetItemMap);
        bean.setPointTypeMap(pointTypeMap);
        bean.setEvaluationItemMap(evaluationItemMap);
        bean.setPoints(points);
        bean.setMeasureMap(measureMap);
        bean.setPlanDetailMap(planDetailMap);
        bean.setJobMap(jobMap);
        bean.setDangerContentMap(dangerContentMap);
        bean.setInvestigatePlanMap(investigatePlanMap);
        bean.setStablePointContrFlag(stablePointContrFlag);
        bean.setDataSourceList(dataSourceList);
        bean.setDataSourceMap(dataSourceMap);
        bean.setTopTypeList(topTypeList);
        bean.setControlTypeGroupItemList(controlTypeGroupItemList);
        bean.setControlTypeGroupItemMap(controlTypeGroupItemMap);
        bean.setTroubleshootingTypeList(troubleshootingTypeList);
        bean.setTroubleshootingTypeMap(troubleshootingTypeMap);
        return bean;
    }

    // 动态生成管控措施 lookup
    private void createRiskMeasureTypeSheet(SXSSFWorkbook workbook, RiskExcelModelBean bean) {
        SXSSFSheet sheet = workbook.createSheet("管控措施类型-对照表");
        //标题行
        SXSSFRow row = sheet.createRow(0);
        createCells(row, new String[]{"管控措施类型", "管控措施二级类型", "管控措施三级类型"}, true, workbook);
        row.setHeightInPoints(20);
        List<RiskMeasureTypeNode> measureTypes = bean.getAllMeasureTypes();
        int rIndex = 1;
        // 管控措施级别
        for (int i = 0; i < measureTypes.size(); i++) {
            List<RiskMeasureTypeNode> secondTypes = measureTypes.get(i).getChilds();
            if (secondTypes == null || secondTypes.isEmpty()) {
                SXSSFRow r = sheet.createRow(rIndex++);
                createCells(r, new String[]{measureTypes.get(i).getMeasureTypeName(), "", ""}, false, workbook);
                continue;
            }
            for (int j = 0; j < secondTypes.size(); j++) {
                List<RiskMeasureTypeNode> thirdTypes = secondTypes.get(j).getChilds();
                if (thirdTypes == null || thirdTypes.isEmpty()) {
                    SXSSFRow r = sheet.createRow(rIndex++);
                    createCells(r, new String[]{measureTypes.get(i).getMeasureTypeName(), secondTypes.get(j).getMeasureTypeName(), ""}, false, workbook);
                    continue;
                }
                for (int k = 0; k < thirdTypes.size(); k++) {
                    SXSSFRow r = sheet.createRow(rIndex++);
                    createCells(r, new String[]{measureTypes.get(i).getMeasureTypeName(), secondTypes.get(j).getMeasureTypeName(),
                            thirdTypes.get(k).getMeasureTypeName()}, false, workbook);
                }
            }
        }
    }

    //创建sheet
    private RiskExcelModelBean createSheetData(RiskExcelModelBean bean, Long analyzeWayId, Integer isTemplate, Integer shared, ExcelExportToolMapBean toolBean, Integer measureTypeFlag, Integer storePointFlag) {
        long a = System.currentTimeMillis();
        SXSSFWorkbook workbook = bean.getWorkbook();
        Integer sheetIndex = bean.getSheetIndex() == null ? Integer.valueOf(0) : bean.getSheetIndex();
        //设置sheet 某一列为文本格式
        CellStyle cellStyle = workbook.createCellStyle();
        DataFormat format = workbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("@"));

        //分析方法
        RiskEvaluationAnalyzeWay analyze = analyzeWayDao.findById(analyzeWayId).orElseThrow(() -> new IllegalArgumentException("分析方法不存在"));
        List<RiskEvaluationAnalyzeMethod> analyzeWayList = analyzeMethodDao.findByWayId(analyzeWayId);
        if (analyze.getEvaluationId() == null) {
            throw new IllegalArgumentException("该分析方法未绑定评估方法");
        }

        //评估方法
        RiskEvaluationAnalyzeWay evaluation = analyzeWayDao.findById(analyze.getEvaluationId()).orElseThrow(() -> new IllegalArgumentException("评估方法不存在"));
        List<RiskEvaluationAnalyzeMethod> evaluationWayList = analyzeMethodDao.findByWayId(evaluation.getId());

        //管控措施
        if (bean.getMaxTypeLevel() == null || bean.getMaxTypeLevel() == 0) {
            throw new IllegalArgumentException("管控措施尚未配置");
        }


        List<BaseTypeGroupItem> controlTypeGroupItemList = toolBean.getControlTypeGroupItemList();
        if (CollectionUtils.isEmpty(controlTypeGroupItemList)) {
            throw new IllegalArgumentException("请在数据字典中配置管控措施");
        }
        //评估数据导出小标题 为以后数据导出做准备
        List<RiskExportDataBean> analyzeBeanList = new ArrayList<>();
        SXSSFSheet sheet = null;
        try {
            sheet = workbook.createSheet(analyze.getName());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new IllegalArgumentException("不支持导出分析方法[" + analyze.getName() + "]");
        }
        SXSSFRow row = null;
        SXSSFCell cell = null;

        //标题
        row = sheet.createRow(0);
        row.setHeightInPoints(20);
        //区域index
        int districtNameIndex = 0;
        //风险点index
        int pointCodeIndex = 0;
        int pointNameIndex = 1;
        int pointTypeIndex = 2;
        //序号
        int index = 3;
        //评估方法 打分
        int controlIndex = index + analyzeWayList.size();
        //管控措施
        int measureTypeIndex = controlIndex + evaluationWayList.size();
        int evalTimeIndex = measureTypeIndex + 2 + 3;
        if (storePointFlag == 0) {
            evalTimeIndex = measureTypeIndex + controlTypeGroupItemList.size() + 3;
        }
        //评估人index
        int evalUserIndex = evalTimeIndex - 1;

        //责任单位index
        int resDepartIndex = 0;
        //隐患问题描述index
        int dangersDescIndex = 0;
        //管控级别
        int controLevelIndex = 0;
        List<RiskExcelTitleBean> titles = new ArrayList<>();


        titles = excelTitleBean("风险单元编号", false, titles, pointCodeIndex);
        analyzeBeanList.add(getExportDataBean(null, null, "风险单元编号", pointCodeIndex));
        sheet.setDefaultColumnStyle(pointCodeIndex, cellStyle);
        titles = excelTitleBean("风险单元名称", true, titles, pointNameIndex);
        analyzeBeanList.add(getExportDataBean(null, null, "风险单元名称", pointNameIndex));
        sheet.setDefaultColumnStyle(pointNameIndex, cellStyle);
        titles = excelTitleBean("风险单元类型", true, titles, pointTypeIndex);
        analyzeBeanList.add(getExportDataBean(null, null, "风险单元类型", pointTypeIndex));
        List<RiskPointType> pointTypes = riskPointTypeDao.findByParentId(null);
        if (!CollectionUtils.isEmpty(pointTypes)) {
            List<String> collect = pointTypes.stream().map(e -> e.getName()).collect(Collectors.toList());
            RiskEvalExcelUtil.getSelectData(workbook, collect, sheet, 1, 100, pointTypeIndex, sheetIndex);
            sheetIndex = sheetIndex + 1;
        }
        sheet.setDefaultColumnStyle(pointTypeIndex, cellStyle);
        titles = excelTitleBean("序号", true, titles, index);
        analyzeBeanList.add(getExportDataBean(null, null, "序号", index));
        sheet.setDefaultColumnStyle(index, cellStyle);

        //分析方法标题
        if (!CollectionUtils.isEmpty(analyzeWayList)) {
            analyzeWayList = analyzeWayList.stream().sorted(Comparator.comparing(RiskEvaluationAnalyzeMethod::getOrderNumber, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        }
        for (int i = 0; i < analyzeWayList.size(); i++) {
            RiskEvaluationAnalyzeMethod method = analyzeWayList.get(i);
            if (method.getIsRequired() != null && method.getIsRequired() == 1) {
                titles = excelTitleBean(method.getName(), true, titles, index + i + 1);
            } else {
                titles = excelTitleBean(method.getName(), false, titles, index + i + 1);
            }
            List<String> list = new ArrayList<>();
            if (method.getContentType() != null && method.getContentType() == 1) {
                List<RiskEvaluationTargetType> targetTypeList = targetTypeDao.findByMethodId(method.getId());
                if (!CollectionUtils.isEmpty(targetTypeList)) {
                    for (RiskEvaluationTargetType targetType : targetTypeList) {
                        List<RiskEvaluationTargetItem> targetItemList = targetItemDao.findByTypeId(targetType.getId());
                        for (RiskEvaluationTargetItem item : targetItemList) {
                            list.add(item.getName());
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(list)) {
                    RiskEvalExcelUtil.getSelectData(workbook, list, sheet, 1, 100, index + i + 1, sheetIndex);
                    sheetIndex = sheetIndex + 1;
                }
            }
            analyzeBeanList.add(getExportDataBean(method.getId(), method.getName(), "分析方法", index + i + 1));
        }

        if (!CollectionUtils.isEmpty(evaluationWayList)) {
            evaluationWayList = evaluationWayList.stream()
                    .sorted(Comparator.comparing(RiskEvaluationAnalyzeMethod::getOrderNumber, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        }

        for (int i = 0; i < evaluationWayList.size(); i++) {
            RiskEvaluationAnalyzeMethod method = evaluationWayList.get(i);
            if (method.getIsRequired() != null && method.getIsRequired() == 1) {
                titles = excelTitleBean(method.getCode(), true, titles, controlIndex + i + 1);
            } else {
                titles = excelTitleBean(method.getCode(), false, titles, controlIndex + i + 1);
            }
            List<String> list = new ArrayList<>();
            if (method.getContentType() != null && method.getContentType() == 0) {
                List<RiskEvaluationTargetType> targetTypeList = targetTypeDao.findByMethodId(method.getId());
                if (!CollectionUtils.isEmpty(targetTypeList)) {
                    for (RiskEvaluationTargetType targetType : targetTypeList) {
                        List<RiskEvaluationTargetItem> targetItemList = targetItemDao.findByTypeId(targetType.getId());
                        for (RiskEvaluationTargetItem item : targetItemList) {
                            if (!list.contains(item.getScore() + "")) {
                                list.add(item.getScore() + "");
                            }
                        }
                    }
                }
                if (!CollectionUtils.isEmpty(list)) {
                    RiskEvalExcelUtil.getSelectData(workbook, list, sheet, 1, 100, controlIndex + i + 1, sheetIndex);
                    sheetIndex = sheetIndex + 1;
                }
            }
            analyzeBeanList.add(getExportDataBean(method.getId(), method.getName(), "控制评估方法", controlIndex + i + 1));
        }

        //管控措施
        if (storePointFlag == 0) {
            for (int i = 0; i < controlTypeGroupItemList.size(); i++) {
                BaseTypeGroupItem item = controlTypeGroupItemList.get(i);
                titles = excelTitleBean(item.getName(), false, titles, measureTypeIndex + i + 1);
                analyzeBeanList.add(getExportDataBean(item.getId(), item.getName(), "管控措施类型", measureTypeIndex + i + 1));
                sheet.setDefaultColumnStyle(measureTypeIndex + i + 1, cellStyle);
            }
        } else {
            titles = excelTitleBean("管控措施类型", true, titles, measureTypeIndex + 1);
            analyzeBeanList.add(getExportDataBean(null, "管控措施类型", "管控措施类型", measureTypeIndex + 1));
            sheet.setDefaultColumnStyle(measureTypeIndex + 1, cellStyle);
            RiskEvalExcelUtil.getSelectData(workbook, controlTypeGroupItemList.stream().map(BaseTypeGroupItem::getName).collect(Collectors.toList()), sheet, 1, 100, measureTypeIndex + 1, sheetIndex);
            sheetIndex = sheetIndex + 1;
//            sheetIndex = fillMeasureTypeList(1, measureTypeIndex + 1, workbook, sheet, sheetIndex);
//            if (bean.getMaxTypeLevel() >= 2) {
//                titles = excelTitleBean("管控措施二级类型", false, titles, measureTypeIndex + 2);
//                analyzeBeanList.add(getExportDataBean(null, "管控措施二级类型", "管控措施二级类型", measureTypeIndex + 2));
//                sheet.setDefaultColumnStyle(measureTypeIndex + 1, cellStyle);
//            }
//            if (bean.getMaxTypeLevel() >= 3) {
//                titles = excelTitleBean("管控措施三级类型", false, titles, measureTypeIndex + 3);
//                analyzeBeanList.add(getExportDataBean(null, "管控措施三级类型", "管控措施三级类型", measureTypeIndex + 3));
//                sheet.setDefaultColumnStyle(measureTypeIndex + 3, cellStyle);
//            }
            int measureTypeContentIndex = measureTypeIndex + 1 + 1;
            titles = excelTitleBean("管控措施内容", true, titles, measureTypeContentIndex);
            analyzeBeanList.add(getExportDataBean(null, "管控措施内容", "管控措施内容", measureTypeContentIndex));
            sheet.setDefaultColumnStyle(measureTypeContentIndex, cellStyle);
        }

        titles = excelTitleBean("评估人工号", true, titles, evalUserIndex - 1);
        analyzeBeanList.add(getExportDataBean(null, "评估人工号", "评估人工号", evalUserIndex - 1));
        sheet.setDefaultColumnStyle(evalUserIndex - 1, cellStyle);
        titles = excelTitleBean("评估人", false, titles, evalUserIndex);
        analyzeBeanList.add(getExportDataBean(null, "评估人", "评估人", evalUserIndex));
        sheet.setDefaultColumnStyle(evalUserIndex, cellStyle);

        titles = excelTitleBean("评估日期", true, titles, evalTimeIndex);
        analyzeBeanList.add(getExportDataBean(null, "评估日期", "评估日期", evalTimeIndex));
        sheet.setDefaultColumnStyle(evalTimeIndex, cellStyle);

        //创建cell
        titles = titles.stream().sorted(Comparator.comparing(RiskExcelTitleBean::getIndex)).collect(Collectors.toList());
        for (int i = 0; i < titles.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(titles.get(i).getTitle());
            if (titles.get(i).getIsRed()) {
                cell.setCellStyle(title(workbook, true));
            } else {
                cell.setCellStyle(title(workbook, false));
            }
        }

        //设置列宽 长度 = 风险点+风险点名称+分析方法+评估时间+评估方法+管控措施字段个数+分级管控字段个数
        for (int i = 0; i < titles.size(); i++) {
            sheet.setColumnWidth(i, 20 * 256);
        }
        //动态内容
        if (isTemplate != null && isTemplate.intValue() == 1) {
            if (shared != null && shared.equals(1)) {
                if (storePointFlag == 0) {
                    //管控横版
                    workbook = getNewStorePointItemData(workbook, sheet, analyzeBeanList, toolBean, analyzeWayId, storePointFlag);
                } else {
                    //管控竖版
                    workbook = getNewStorePointItemData(workbook, sheet, analyzeBeanList, toolBean, analyzeWayId, storePointFlag);
                }
            }
        } else if (isTemplate != null && isTemplate.intValue() == 2) {
            //TODO
            workbook = getOldItemData(workbook, sheet, analyze, analyzeBeanList, shared);
        }
        bean.setWorkbook(workbook);
        bean.setSheetIndex(sheetIndex);
        long b = System.currentTimeMillis();
        System.out.println(analyze.getName() + "======花费时间:" + (b - a));
        return bean;
    }

    private SXSSFWorkbook getNewStorePointItemData(SXSSFWorkbook workbook, SXSSFSheet sheet, List<RiskExportDataBean> analyzeBeanList, ExcelExportToolMapBean toolBean, Long analyzeWayId, Integer storePointFlag) {
        Map<Long, BaseUser> userMap = toolBean.getUserMap();
        Map<Long, BpDepart> departMap = toolBean.getDepartMap();
        Map<Long, RiskControllevels> controLevelMap = toolBean.getControLevelMap();
        Map<Long, RiskEvaluationTargetItem> targetItemMap = toolBean.getTargetItemMap();
        Map<String, RiskPointType> pointTypeMap = toolBean.getPointTypeMap();
        Map<Long, List<RiskPointEvaluationItem>> evaluationItemMap = toolBean.getEvaluationItemMap();
        List<RiskPoint> points = toolBean.getPoints();

        if (!CollectionUtils.isEmpty(points)) {
            //标题
            int index = 1;
            List<RiskPointEvaluationItem> itemList = new ArrayList<>();
            for (RiskPoint point : points) {
                //控制风险评估
                Long evaluationUserId = null;
                RiskPointEvaluationBusiness evaluation = pointEvaluationBusinessDao.getLastPointEvaluationByPointIdAndAnalyzeWayId(point.getId(), 1, analyzeWayId);
                if (evaluation != null) {
                    if (StringUtils.isNotBlank(evaluation.getEvaluationUserIds())) {
                        evaluationUserId = StringUtil.covertJsonToLongList(evaluation.getEvaluationUserIds()).get(0);
                    }
                    List<RiskPointEvaluationDetail> detailList = riskPointEvaluationDetailDao.findByPointEvaluationId(evaluation.getId());
                    Map<Long, List<RiskPointEvaluationDetail>> itemDeatilMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(detailList)) {
                        itemDeatilMap = detailList.stream().collect(Collectors.groupingBy(RiskPointEvaluationDetail::getItemId));
                    }
                    if (!CollectionUtils.isEmpty(evaluationItemMap)) {
                        itemList = evaluationItemMap.get(evaluation.getId());
                    }
                    if (!CollectionUtils.isEmpty(itemList)) {
                        if (storePointFlag == 1) {
                            for (int j = 0; j < itemList.size(); j++) {
                                RiskPointEvaluationjsonItemBean itemBean = riskEvaluationBusinessService.getjsonItemBean(itemList, targetItemMap, itemDeatilMap, j, toolBean, null);
                                Map<Long, String> contents = itemBean.getContents();
                                if (!CollectionUtils.isEmpty(contents)) {
                                    for (Map.Entry<Long, String> entry : contents.entrySet()) {
                                        SXSSFRow row = sheet.createRow(index);
                                        RiskPointType pType = null;
                                        if (!CollectionUtils.isEmpty(pointTypeMap)) {
                                            pType = pointTypeMap.get(point.getType());
                                        }
                                        if (pType == null) {
                                            //兼容部分将类型名称当做编号的旧数据
                                            pType = riskPointTypeDao.findFirstByName(point.getType());
                                            if (pType == null) {
                                                throw new IllegalArgumentException("风险点+(" + point.getCode() + ")类型配置不正确");
                                            }
                                        }
                                        Long key = entry.getKey();
                                        String value = entry.getValue();
                                        for (RiskExportDataBean rb : analyzeBeanList) {
                                            SXSSFCell cell = row.createCell(rb.getIndex());
                                            cell.setCellType(CellType.STRING);
                                            BaseUser bu;
                                            BpDepart depart;
                                            switch (rb.getType()) {
                                                case "风险单元编号":
                                                    cell.setCellValue(point.getCode());
                                                    break;
                                                case "风险单元名称":
                                                    cell.setCellValue(point.getName());
                                                    break;
                                                case "风险单元类型":
                                                    cell.setCellValue(pType.getName());
                                                    break;
                                                case "序号":
                                                    cell.setCellValue(itemBean.getIndex());
                                                    break;
                                                case "分析方法":
                                                    cell.setCellValue(itemBean.getAnalyseContent().get(rb.getId()));
                                                    break;
                                                case "控制评估方法":
                                                    cell.setCellValue(itemBean.getStableContents().get(rb.getId()));
                                                    break;
                                                case "评估人工号":
                                                    bu = userMap.get(evaluationUserId);
                                                    if (bu != null) {
                                                        cell.setCellValue(bu.getCode());
                                                    }
                                                    break;
                                                case "评估人":
                                                    bu = userMap.get(evaluationUserId);
                                                    if (bu != null) {
                                                        cell.setCellValue(bu.getRealName());
                                                    }
                                                    break;
                                                case "评估日期":
                                                    cell.setCellValue(SimpleDateFormatCache.getYmdhms().format(evaluation.getEvaluationDate()));
                                                    break;
                                                case "管控措施类型":
                                                    if (storePointFlag == 1) {
                                                        BaseTypeGroupItem item = toolBean.getControlTypeGroupItemMap().get(key);
                                                        if (item != null) {
                                                            cell.setCellValue(item.getName());
                                                        }
                                                    } else if (storePointFlag == 0) {
                                                        if (rb.getId().equals(key)) {
                                                            cell.setCellValue(value);
                                                        }
                                                    }
                                                    break;
                                                case "管控措施内容":
                                                    if (storePointFlag == 1) {
                                                        cell.setCellValue(value);
                                                    }
                                                    break;
                                                case "责任人工号":
                                                    bu = userMap.get(itemBean.getResponseUserIds().get(0));
                                                    if (bu != null) {
                                                        cell.setCellValue(bu.getCode());
                                                    }
                                                    break;
                                                case "责任人":
                                                    bu = userMap.get(itemBean.getResponseUserIds().get(0));
                                                    if (bu != null) {
                                                        cell.setCellValue(bu.getRealName());
                                                    }
                                                    break;
                                                case "责任单位编码":
                                                    depart = departMap.get(itemBean.getResponseDepartIds().get(0));
                                                    if (depart != null) {
                                                        cell.setCellValue(depart.getCode());
                                                    }
                                                    break;
                                                case "责任单位":
                                                    depart = departMap.get(itemBean.getResponseDepartIds().get(0));
                                                    if (depart != null) {
                                                        cell.setCellValue(depart.getName());
                                                    }
                                                    break;
                                                case "管控级别":
                                                    RiskControllevels bean = controLevelMap.get(itemBean.getControlLevelIds().get(0));
                                                    if (bean != null) {
                                                        cell.setCellValue(bean.getName());
                                                    }
                                                    break;
                                            }
                                        }
                                        index++;
                                    }
                                }
                            }
                        } else {
                            for (int j = 0; j < itemList.size(); j++) {
                                RiskPointEvaluationjsonItemBean itemBean = riskEvaluationBusinessService.getjsonItemBean(itemList, targetItemMap, itemDeatilMap, j, toolBean, null);
                                Map<Long, String> contents = itemBean.getContents();

                                SXSSFRow row = sheet.createRow(index);
                                RiskPointType pType = null;
                                if (!CollectionUtils.isEmpty(pointTypeMap)) {
                                    pType = pointTypeMap.get(point.getType());
                                }
                                if (pType == null) {
                                    //兼容部分将类型名称当做编号的旧数据
                                    pType = riskPointTypeDao.findFirstByName(point.getType());
                                    if (pType == null) {
                                        throw new IllegalArgumentException("风险点+(" + point.getCode() + ")类型配置不正确");
                                    }
                                }
                                for (RiskExportDataBean rb : analyzeBeanList) {
                                    SXSSFCell cell = row.createCell(rb.getIndex());
                                    cell.setCellType(CellType.STRING);
                                    BaseUser bu;
                                    BpDepart depart;
                                    switch (rb.getType()) {
                                        case "风险单元编号":
                                            cell.setCellValue(point.getCode());
                                            break;
                                        case "风险单元名称":
                                            cell.setCellValue(point.getName());
                                            break;
                                        case "风险单元类型":
                                            cell.setCellValue(pType.getName());
                                            break;
                                        case "序号":
                                            cell.setCellValue(itemBean.getIndex());
                                            break;
                                        case "分析方法":
                                            cell.setCellValue(itemBean.getAnalyseContent().get(rb.getId()));
                                            break;
                                        case "控制评估方法":
                                            cell.setCellValue(itemBean.getStableContents().get(rb.getId()));
                                            break;
                                        case "评估人工号":
                                            bu = userMap.get(evaluationUserId);
                                            if (bu != null) {
                                                cell.setCellValue(bu.getCode());
                                            }
                                            break;
                                        case "评估人":
                                            bu = userMap.get(evaluationUserId);
                                            if (bu != null) {
                                                cell.setCellValue(bu.getRealName());
                                            }
                                            break;
                                        case "评估日期":
                                            cell.setCellValue(SimpleDateFormatCache.getYmdhms().format(evaluation.getEvaluationDate()));
                                            break;
                                        case "管控措施类型":
                                            if (storePointFlag == 0) {
                                                if (!CollectionUtils.isEmpty(contents)) {
                                                    for (Map.Entry<Long, String> entry : contents.entrySet()) {
                                                        Long key = entry.getKey();
                                                        String value = entry.getValue();
                                                        if (rb.getId().equals(key)) {
                                                            cell.setCellValue(value);
                                                        }
                                                    }
                                                }

                                            }
                                            break;
                                        case "责任人工号":
                                            bu = userMap.get(itemBean.getResponseUserIds().get(0));
                                            if (bu != null) {
                                                cell.setCellValue(bu.getCode());
                                            }
                                            break;
                                        case "责任人":
                                            bu = userMap.get(itemBean.getResponseUserIds().get(0));
                                            if (bu != null) {
                                                cell.setCellValue(bu.getRealName());
                                            }
                                            break;
                                        case "责任单位编码":
                                            depart = departMap.get(itemBean.getResponseDepartIds().get(0));
                                            if (depart != null) {
                                                cell.setCellValue(depart.getCode());
                                            }
                                            break;
                                        case "责任单位":
                                            depart = departMap.get(itemBean.getResponseDepartIds().get(0));
                                            if (depart != null) {
                                                cell.setCellValue(depart.getName());
                                            }
                                            break;
                                        case "管控级别":
                                            RiskControllevels bean = controLevelMap.get(itemBean.getControlLevelIds().get(0));
                                            if (bean != null) {
                                                cell.setCellValue(bean.getName());
                                            }
                                            break;
                                    }
                                }
                                index++;
                            }
                        }
                    }
                }
            }
        }
        return workbook;
    }

    //旧评估数据按新模板导出
    @Override
    public SXSSFWorkbook getOldItemData(SXSSFWorkbook workbook, SXSSFSheet sheet, RiskEvaluationAnalyzeWay analyze,
                                        List<RiskExportDataBean> analyzeBeanList,
                                        Integer shared) {
        List<RiskPointEvaluationBean> dataList = new ArrayList<>();
        List<RiskPoint> points = new ArrayList<>();
        if (shared == null || shared == 0) {
            points = riskPointDao.findByTimeIsNotNull();
        } else if (shared == 1) {
            points = riskPointDao.findByTimeIsNotNullAndShared();
        }
        for (RiskPoint point : points) {
            RiskPointEvaluationBean riskPointEvaluationBean = riskPointService.queryEvaluationTemplate(point.getId(), analyze.getCode().toUpperCase(), false);
            if (riskPointEvaluationBean != null) {
                riskPointEvaluationBean.setRiskPointId(point.getId());
                dataList.add(riskPointEvaluationBean);
            }
        }
        if (!CollectionUtils.isEmpty(dataList)) {
            int rowIndex = 1;
            for (int i = 0; i < dataList.size(); i++) {
                int cellIndex = 3;
                if (shared == null || shared == 0) {
                    cellIndex = 5;
                }
                RiskPointEvaluationBean bean = dataList.get(i);
                RiskPoint point = riskPointDao.findById(bean.getRiskPointId()).get();
                String pointCode = point.getCode();//风险点编号
                String pointName = point.getName();//风险点名称
                String pointType = point.getType();
                Long controlLevelId = point.getControlLevelId();
                String controlLevelName = null;
                if (controlLevelId != null) {
                    controlLevelName = ControlLevels.findControlLevelName(controlLevelId.intValue());//管控层级
                }
                BaseUser responsibleUser = point.getResponsibleUser();
                String responsibleUserCode = null;
                String responsibleUserName = null;
                if (responsibleUser != null) {
                    responsibleUserCode = responsibleUser.getCode();//责任人工号;
                    responsibleUserName = responsibleUser.getRealName();//责任人名称
                }
                BpDepart responsibleDepart = point.getResponsibleDepart();
                String responsibleDepartCode = null;
                String responsibleDepartName = null;
                if (responsibleDepart != null) {
                    responsibleDepartCode = responsibleDepart.getCode();//责任部门工号
                    responsibleDepartName = responsibleDepart.getName();//责任部门名称
                }
                RiskPointType pType = riskPointTypeDao.findByCode(pointType);//风险点类型
                if (pType == null) {
                    //兼容部分将类型名称当做编号的旧数据
                    pType = riskPointTypeDao.findFirstByName(pointType);
                    if (pType == null) {
                        throw new IllegalArgumentException("风险点+(" + pointCode + ")类型配置不正确");
                    }
                }
                String pointTypeName = pType.getName();//风险点类型
                RiskDistrict riskDistrict = point.getRiskDistrict();
                String riskDistrictName = null;//风险区域名称
                String riskDistrictCode = null;//风险区域编码
                String analyzeTime = bean.getAnalyzeTime();//评估时间
                String analyzeUserName = bean.getAnalyzeUserName();//评估人工号
                String analyzeUserCode = null;
                Long analyzeUserId = bean.getAnalyzeUserId();
                if (analyzeUserId != null) {
                    if (baseUserDao.findById(analyzeUserId).isPresent()) {
                        analyzeUserCode = baseUserDao.findById(analyzeUserId).get().getCode();
                    }
                }
                if (riskDistrict != null) {
                    riskDistrictName = riskDistrict.getName();
                    riskDistrictCode = riskDistrict.getCode();
                }
                List<RiskPointEvaluationItemBean> items = bean.getItems();
                if (CollectionUtils.isEmpty(items)) {
                    continue;
                }
                for (int j = 0; j < items.size(); j++) {
                    RiskPointEvaluationItemBean itemBean = items.get(j);
                    Integer indexNumber = j + 1;//序号
                    getOldDataRowCellValue(sheet, rowIndex, indexNumber, cellIndex, pointCode, pointName, pointTypeName, analyzeUserCode, analyzeUserName, analyzeTime,
                            controlLevelName, responsibleDepartCode, responsibleDepartName, responsibleUserCode, responsibleUserName,
                            riskDistrictCode, riskDistrictName, analyzeBeanList, itemBean);
                    rowIndex++;
                }
            }
        }
        return workbook;
    }

    @Override
    public void exportEvalErrorMessages(List<String> errorMessage, HttpServletResponse response) {
        //创建文件名
        String fileName = "评估错误提示" + DateUtil.format(new Date(), DateUtils.STYLE_yyyyMMddHHmmss) + ".txt";
        //设置返回信息数据
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        //创建输出流
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        String enter = "\r\n";
        //创建拼接字段
        StringBuffer write;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            //循环数据
            if (!CollectionUtils.isEmpty(errorMessage)) {
                for (String str : errorMessage) {
                    write = new StringBuffer();
                    //写入数据
                    write.append(str);
                    //完成之后进行换行
                    write.append(enter);
                    //写入指定格式
                    buff.write(write.toString().getBytes("utf-8"));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

    }

    //旧数据---导出每行数据
    private void getOldDataRowCellValue(SXSSFSheet sheet, Integer rowIndex, Integer indexNumber, Integer cellIndex, String pointCode,
                                        String pointName, String pointTypeName, String analyzeUserCode, String analyzeUserName, String analyzeTime, String controlLevelName,
                                        String responsibleDepartCode, String responsibleDepartName, String responsibleUserCode, String responsibleUserName, String riskDistrictCode,
                                        String riskDistrictName, List<RiskExportDataBean> analyzeBeanList, RiskPointEvaluationItemBean itemBean) {
        SXSSFRow row = sheet.createRow(rowIndex);
        SXSSFCell cell0 = row.createCell(0);
        cell0.setCellValue(pointCode);
        SXSSFCell cell1 = row.createCell(1);
        cell1.setCellType(CellType.STRING);
        cell1.setCellValue(pointName);
        SXSSFCell cell2 = row.createCell(2);
        cell2.setCellValue(pointTypeName);
        SXSSFCell cellIndexNumber = row.createCell(cellIndex);
        cellIndexNumber.setCellValue(indexNumber);
        if (cellIndex == 5) {
            SXSSFCell cella = row.createCell(cellIndex - 1);
            cella.setCellValue(riskDistrictCode);
            cella.setCellType(CellType.STRING);
            SXSSFCell cellb = row.createCell(cellIndex - 2);
            cellb.setCellValue(riskDistrictName);
        }
        Double L = null;
        Double S = null;
        for (RiskExportDataBean rb : analyzeBeanList) {
            SXSSFCell cell = row.createCell(rb.getIndex());
            if (rb.getType().equals("分析方法")) {
                if (rb.getName().equals("作业步骤") || rb.getName().equals("检查项目")) {
                    cell.setCellValue(itemBean.getCheckItem());
                } else if (rb.getName().equals("标准")) {
                    cell.setCellValue(itemBean.getStandard());
                } else if (rb.getName().equals("不符合情况及后果") || rb.getName().equals("可能发生的事故类型及后果")) {
                    cell.setCellValue(itemBean.getConsequence());
                } else if (rb.getName().equals("风险源或潜在事件")) {
                    cell.setCellValue(itemBean.getRiskSource());
                }
            } else if (rb.getType().equals("评估方法")) {
                if (rb.getName().equals("事故事件发生的可能性（L）") || rb.getName().equals("事故发生的可能性（L）")) {
                    if (itemBean.getLikehood() != null && !"0".equals(itemBean.getLikehood().toString())) {
                        try {
                            cell.setCellValue(RiskEvalExcelUtil.getFloatDecimal((Float) itemBean.getLikehood()));
                            L = ((Float) itemBean.getLikehood()).doubleValue();
                        } catch (Exception e) {
                            cell.setCellValue((Integer) itemBean.getLikehood());
                            L = ((Integer) itemBean.getLikehood()).doubleValue();
                        }
                    }
                } else if (rb.getName().equals("事件后果严重性（S）")) {
                    if (itemBean.getSeverity() != null && itemBean.getSeverity() > 0) {
                        try {
                            cell.setCellValue(String.valueOf(itemBean.getSeverity()).substring(1, 2));
                            S = Double.valueOf(String.valueOf(itemBean.getSeverity()).substring(1, 2));
                        } catch (Exception e) {
                            S = null;
                        }
                    }
                } else if (rb.getName().equals("安全风险等级判定准则（R）及控制措施")) {
                    Double riskValue = null;
                    if (S != null && L != null) {
                        riskValue = S * L;
                    } else if (S != null && L == null) {
                        riskValue = S;
                    } else if (S == null && L != null) {
                        riskValue = L;
                    } else {
                        riskValue = itemBean.getRiskValue().doubleValue();
                    }
                    cell.setCellValue(riskValue);
                } else if (rb.getName().equals("暴露于危险环境的频繁程度（E）")) {
                    if (itemBean.getExposure() != null && itemBean.getExposure() > 0) {
                        cell.setCellValue(RiskEvalExcelUtil.getFloatDecimal(itemBean.getExposure()));
                    }
                } else if (rb.getName().equals("发生事故事件偏差产生的后果严重性（C）")) {
                    if (itemBean.getConsequenceLevel() != null && itemBean.getConsequenceLevel() > 0) {
                        cell.setCellValue(String.valueOf(itemBean.getConsequenceLevel()).substring(1));
                    }
                } else if (rb.getName().equals("安全风险等级判定准则（D）及控制措施")) {
                    if (itemBean.getDanger() != null) {
                        cell.setCellValue(RiskEvalExcelUtil.getFloatDecimal(itemBean.getDanger()));
                    }
                }
            } else if (rb.getType().equals("评估人工号")) {
                cell.setCellValue(analyzeUserCode);
            } else if (rb.getType().equals("评估人")) {
                cell.setCellValue(analyzeUserName);
            } else if (rb.getType().equals("评估时间")) {
                cell.setCellValue(analyzeTime);
            } else if (rb.getType().equals("管控措施")) {
                if (rb.getName().equals("工程技术措施")) {
                    cell.setCellValue(itemBean.getControlMethodTech());
                } else if (rb.getName().equals("管理措施")) {
                    cell.setCellValue(itemBean.getControlMethodManage());
                } else if (rb.getName().equals("培训教育措施")) {
                    cell.setCellValue(itemBean.getControlMethodTrain());
                } else if (rb.getName().equals("个体防护措施")) {
                    cell.setCellValue(itemBean.getControlMethodProtect());
                } else if (rb.getName().equals("应急处理措施")) {
                    cell.setCellValue(itemBean.getControlMethodEmegency());
                }
            } else if (rb.getType().equals("责任人工号")) {
                cell.setCellValue(responsibleUserCode);
            } else if (rb.getType().equals("责任人")) {
                cell.setCellValue(responsibleUserName);
            } else if (rb.getType().equals("责任单位编码")) {
                cell.setCellValue(responsibleDepartCode);
            } else if (rb.getType().equals("责任单位")) {
                cell.setCellValue(responsibleDepartName);
            } else if (rb.getType().equals("管控级别")) {
                cell.setCellValue(controlLevelName);
            }
            cell.setCellType(CellType.STRING);
        }
    }

    private void createCells(SXSSFRow row, String[] titleTexts, boolean isTitle, SXSSFWorkbook workbook) {
        int index = 0;
        for (String text : titleTexts) {
            SXSSFCell c = row.createCell(index++);
            c.setCellStyle(isTitle ? title(workbook, false) : text(workbook));
            c.setCellValue(text);
            row.getSheet().setColumnWidth(index - 1, 20 * 256);

        }

    }

    //设置抬头是否必填
    private List<RiskExcelTitleBean> excelTitleBean(String title, Boolean isRed, List<RiskExcelTitleBean> titles, Integer index) {
        RiskExcelTitleBean bean = new RiskExcelTitleBean();
        bean.setTitle(title);
        bean.setIsRed(isRed);
        bean.setIndex(index);
        titles.add(bean);
        return titles;
    }


    //获取列数据
    private RiskExportDataBean getExportDataBean(Long id, String name, String type, Integer index) {
        RiskExportDataBean bean = new RiskExportDataBean();
        bean.setId(id);
        bean.setName(name);
        bean.setType(type);
        bean.setIndex(index);
        return bean;
    }


    //小标题的样式
    public CellStyle title(Workbook wb, Boolean isRed) {
        return RiskEvalExcelUtil.title(wb, isRed, 12);
    }

    //文字样式
    public CellStyle text(Workbook wb) {
        return RiskEvalExcelUtil.text(wb, 10, false);
    }

}
